package Ijswitch

import (
	"fmt"
	"io/fs"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

// Win 系统实现类
type WinJswitchParam struct {
	ScanPath string
}

func (param *WinJswitchParam) ScanJDK() []Jdk {

	fmt.Println("进行 Win 的扫描: " + param.ScanPath)

	var result []Jdk = []Jdk{}

	err := filepath.Walk(param.ScanPath, func(path string, info fs.FileInfo, err error) error {
		if err != nil {
			return err
		}
		// if info.IsDir() {
		// 	fmt.Println("Directory:", path)
		// } else {
		// 	fmt.Println("File:", path)
		// }

		if strings.ToLower(info.Name()) == "javac.exe" {
			fmt.Println("找到 JDK: " + path)

			output, err := exec.Command(path, "-version").CombinedOutput()

			if err != nil {
				log.Printf("exec.Command error: %v \n", err)
				return nil
			}

			fmt.Printf("运行 %s 结果: %v \n", path, string(output))

			splits := strings.Split(string(output), " ")
			if len(splits) < 2 {
				return nil
			}

			tempPath := strings.Replace(path,
				string(filepath.Separator)+"bin"+string(filepath.Separator)+"javac.exe",
				"",
				-1)

			thisJdk := Jdk{
				Version: "jdk_" + strings.Replace(splits[1], NewLine, "", -1),
				Path:    tempPath,
			}

			result = append(result, thisJdk)
		}

		return nil
	})

	if err != nil {
		log.Fatalf("filepath.Walk error: %v \n", err)
	}

	return result
}

func (param *WinJswitchParam) SetEnv(idx int, jdkList *[]Jdk) error {

	if idx < 0 || idx >= len(*jdkList) {
		return fmt.Errorf("index out of range")
	}

	// 校验路径是否存在
	if _, err := os.Stat((*jdkList)[idx].Path); os.IsNotExist(err) {
		return fmt.Errorf("path not exist")
	}

	// 设置 JAVA_HOME 环境变量
	output, err := exec.Command("cmd", "/C", "setx /M JAVA_HOME "+(*jdkList)[idx].Path).CombinedOutput()
	if err != nil {
		log.Printf("exec.Command error: %v \n", err)
		return fmt.Errorf("set env error: %v", err)
	}

	// 创建GBK编码器
	gbkEncoder := simplifiedchinese.GBK.NewDecoder()

	// 将GBK编码的字节数组转换为字符串
	gbkStr, _, _ := transform.Bytes(gbkEncoder, output)

	fmt.Printf("执行结果: %v \n", string(gbkStr))

	return nil
}
